///> 串口数据流驱动

#include "uartstream.hpp"
#include "SEGGER_RTT.h"

using namespace device;
using namespace systemos;

static stream::StreamPackTPDF mSendPack;  ///数据流缓存
static stream::StreamPackTPDF mRecPack;  ///数据流缓存

static stream *mSendStream;
static stream *mRecStream;
static rs485 *mUart;

static void UartStreamThread(void *args)
{	
	uint16_t len, i;

	while(1)
	{
		Method::Sleep(1);
		len = mUart->Read(mRecPack.ucBuff);
		if(len && (len < 256))
		{
			mRecPack.usLen = len;
			mSendStream->Public(&mRecPack); ///> 串口发布数据
		}
		if(mRecStream->Subscribe(&mSendPack)) ///>串口有订阅数据
		{
			mUart->Write(mSendPack.ucBuff, mSendPack.usLen); ///> 串口订阅发送
		}
	}
}

void UartStreamInit(uint32_t uiBaud, uart::UartParityTPDF tUartParity)
{
	mSendStream = new stream(UARTSTREAM_PUBLIC_NAME, stream::STREAM_DIRECT_PUBLIC, sizeof(stream::StreamPackTPDF));  ///> 串口数据发布
	mRecStream = new stream(UARTSTREAM_SUBSCRIBE_NAME, stream::STREAM_DIRECT_SUBSCRIBE, sizeof(stream::StreamPackTPDF)); ///> 串口数据订阅
	
	gpio::GpioPinTPDF tPort;
	tPort.GpioPort = APP_UART_DE_PORT;
	tPort.GpioPin = APP_UART_DE_PIN;
	
	mUart = new rs485(uart::UART_INSTANCE_3, mSendPack.ucBuff, mRecPack.ucBuff, STREAM_MAX_BUFFLEN, &tPort); ///> 485 串口发送接收
	mUart->BaudRate = uiBaud;
	mUart->Parity = tUartParity;
	mUart->Open();
	
	threados *t1 = new threados(UartStreamThread);
	t1->Name = "stream";
	t1->Prio = 0;
	t1->StackDeep = 64;
	t1->Start();
}

void UartChangeParam(uint32_t uiBaud, uart::UartParityTPDF tUartParity)
{
	mUart->ParamSet(tUartParity,uiBaud);
}
